#!/usr/bin/perl -wT
use CGI qw(:standard);
use Fcntl qw(:flock :seek);
use Email::Valid;
use strict;


print header;
print start_html("Registration Results");

my $gamename = param('gamename');
my $username = param('username');
my $password1 = param('password1');
my $password2 = param('password2');
my $email = param('email');

# First, do some data validation.

# be sure the username is alphanumeric - no spaces or funny characters
# also, require it to be at least 3 chars long
if ($username !~ /^\w{3,}$/) {
    &dienice("Please use an alphanumeric username at least 3 letters long, with no spaces.");   
}

# be sure the password isn't blank or shorter than 6 chars
if (length($password1) < 6) {
    &dienice("Please enter a password at least 6 characters long.");
}

if ($password1 ne $password2 ) {
	&dienice("Passwords do not match");
}

unless (Email::Valid->address($email)) {
   &dienice("`$email' doesn't appear to be a valid e-mail address.");
}

# now encrypt the password
my $encpass = &encrypt($password1);

# open the password file for read-write
my $passfile = '/var/www/cgi-bin/data/passwd';
open(PASSF,"+<$passfile") or &dienice("Can't open password file.");
flock(PASSF, LOCK_EX);          # lock the file (exclusively)
seek(PASSF, 0, SEEK_SET);       # rewind to beginning
my @passf = <PASSF>;            # read entire file

# the structure of the passwd file is:
# username:passwd:email:level:active
# username:passwd:email:level:active
# ...etc., with each user's record on a separate line.
# here we're going to loop through and make sure the new username
# doesn't already exist in the htpasswd file.
foreach my $i (@passf) {
    chomp($i);
    my ($user,$pass,$email,$level,$active,$gname) = split(/\,/,$i);
    if ($user eq $username) {
       &dienice("The username `$username' is already in use. Please choose another.");
   }
}

# everything seems clear now, so append the info to the password file.
my $level="10";	# this is the default USER level
seek(PASSF, 0, SEEK_END);       # go to EOF
print PASSF "$username,$encpass,$email,$level,0,$gamename\n";
close(PASSF);

print qq(<p>Congratulations $gamename You're now registered!<br><Your username is <b>$username</b>, and your 
password is <b>$password1</b>.<br>An administrator will email you when your account has been activated.</p>\n);

print end_html;

sub encrypt {
    my($plain) = @_;
    my @salt = ('a'..'z', 'A'..'Z', '0'..'9', '.', '/');
    return crypt($plain, $salt[int(rand(@salt))] . $salt[int(rand(@salt))] );
}

sub dienice {
    my($msg) = @_;
	print "<h1>Musketeers (Shoreline)<h1>";
    print "<h2>Error</h2>\n";
    print $msg;
    exit;
}


